package com.us.usws.site.ws.resource;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.Consumes;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.us.usws.biz.WSResourceURIReplacer;
import com.us.usws.biz.sms.SMSSenderProxy;
import com.us.usws.common.CommonUtils;
import com.us.usws.common.SiteConstants;
import com.us.usws.common.exception.SMSSendException;
import com.us.usws.model.domain.Meeting;
import com.us.usws.model.domain.box.BoxTheme;
import com.us.usws.model.domain.channel.Channel;
import com.us.usws.model.domain.system.MobileAuth;
import com.us.usws.service.cud.MobileAuthCUDService;
import com.us.usws.service.ro.BoxThemeROService;
import com.us.usws.service.ro.ChannelROService;
import com.us.usws.service.ro.MeetingROService;
import com.us.usws.site.ws.entity.WSEntity;
import com.us.usws.site.ws.entity.WSEntityFactory;
import com.us.usws.site.ws.entity.indexes.WSIndexesEntityPackGenerator;
import com.us.usws.site.ws.entity.shared.WSSharedEntityPackGenerator;
import com.us.usws.site.ws.entity.shared.WSSharedEntityPackGenerator.PageUrlCallback;
import com.us.usws.support.uitls.ServiceFactory;
import com.us.usws.support.uitls.SimpleDataPageUtil;
import com.us.usws.support.uitls.SiteWebContext;

/**
 * User webservice
 */
@Path("/")
public class IndexesResource {

	private static Log log = LogFactory.getFactory().getInstance(ChannelResource.class);

	private ChannelROService cService = ServiceFactory.getInstance().getService(ChannelROService.class);
	private MeetingROService mService = ServiceFactory.getInstance().getService(MeetingROService.class);
	private MobileAuthCUDService maS = ServiceFactory.getInstance().getService(MobileAuthCUDService.class);

	@GET
	@Path("/index.json")
	//@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
	@Produces(MediaType.APPLICATION_JSON)
	// + "; charset=UTF-8"
	public WSEntity getMainChannels() {
		List<Channel> results = cService.getHomepageChannels();

		WSEntity ret = WSIndexesEntityPackGenerator.getInstance().getIndexChannelPack(results);

		return ret;
	}

	@GET
	@Path("/my_channels.json")
	//@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
	@Produces(MediaType.APPLICATION_JSON)
	public WSEntity getMyChannels(@Context HttpServletRequest request, @QueryParam("focus_channel_id") String focusChannelUid) {
		SiteWebContext wc = new SiteWebContext(request, null);
		String userUid = wc.getEpUserId();

		//results
		List<Channel> results;
		if (userUid == null) {
			//non login user
			results = cService.getNonLoginChannels(focusChannelUid);
		} else {
			results = cService.getLoginChannels(userUid, focusChannelUid);
		}

		WSEntity ret = WSIndexesEntityPackGenerator.getInstance().getMyChannelPack(results, focusChannelUid);

		return ret;
	}

	@POST
	@Path("/authcodes.json")
	@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
	@Produces(MediaType.APPLICATION_JSON)
	public WSEntity getForgotPasswdAuthCode(@Context HttpServletRequest request, @Context HttpServletResponse response,
			@FormParam("mobile") String mobileNo) {
		String errMsg301 = "\u624b\u673a\u53f7\u7801\u683c\u5f0f\u9519\u8bef";
		String successMsg = "\u9a8c\u8bc1\u7801\u5df2\u7ecf\u53d1\u9001\u5230\u624b\u673a";

		if (!CommonUtils.isValidMobileNo(mobileNo)) {
			return getReturnEntity(errMsg301, (short) 301);
		}

		//String realMobileNo = mobileNo.substring(mobileNo.length() - 11, mobileNo.length());

		//site context
		SiteWebContext swc = new SiteWebContext(request, response);
		//gen auth
		MobileAuth ma = maS.generateNewForgotPasswordAuth(mobileNo, swc.getEpToken(), swc.getEpUserId());
		log.debug("{UserForgotPasswd} :: Generate MobileAuth: id=[" + ma.getId() + "], authCode=[" + ma.getAuthCode()
				+ "], where mobileNo=[" + mobileNo + "], epToken=[" + swc.getEpToken() + "], epUserid=[" + swc.getEpUserId() + "].");

		//content
		String content = "\u60a8\u597d\uff0c\u672c\u6b21\u9a8c\u8bc1\u7801\u4e3a" + ma.getAuthCode()
				+ "\u3002\u777f\u7acb\u5357\u65b9\u3002";
		try {
			SMSSenderProxy.getSMSSender().send(mobileNo, content);
		} catch (SMSSendException e) {
			log.warn("{UserForgotPasswd} :: Send SMS failed.", e);
			return getReturnEntity(errMsg301, (short) 301);
		}

		return getReturnEntity(successMsg, (short) 200);
	}

	@GET
	@Path("/meetings.json")
	//@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
	@Produces(MediaType.APPLICATION_JSON)
	public WSEntity getUserMeetings(@Context HttpServletRequest request, @QueryParam("page_size") int pageSize,
			@QueryParam("page") int pageNo) {

		SiteWebContext wc = new SiteWebContext(request, null);
		final String userUid = wc.getEpUserId();

		if (pageSize < 1) {
			pageSize = SiteConstants.DFT_MEETING_PAGE_SIZE;
		}
		if (pageNo < 1) {
			pageNo = 1;
		}

		int cnt = mService.getMeetingCountByUsersAny(userUid);
		final SimpleDataPageUtil pu = new SimpleDataPageUtil(pageSize, cnt);
		pu.setPageNo(pageNo);
		List<Meeting> results = mService.getMeetingsByUsersAny(userUid, pu.getStart(), pageSize);

		WSEntity ret = WSSharedEntityPackGenerator.getInstance().getMeetingsPack(results, pu, new PageUrlCallback() {

			@Override
			public String getPrevPageUrl() {
				return WSResourceURIReplacer.getMyMeetingsURLWithPageNo(userUid, pu.getPageNo() - 1, pu.getPageCount());
			}

			@Override
			public String getNextPageUrl() {
				return WSResourceURIReplacer.getMyMeetingsURLWithPageNo(userUid, pu.getPageNo() + 1, pu.getPageCount());
			}
		});
		return ret;
	}

	@GET
	@Path("/themes.json")
	//@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
	@Produces(MediaType.APPLICATION_JSON)
	public WSEntity geThemes() {
		BoxThemeROService service = ServiceFactory.getInstance().getService(BoxThemeROService.class);
		List<BoxTheme> themes = service.getAllBoxThemes();

		WSEntity ret = WSIndexesEntityPackGenerator.getInstance().getThemes(themes, true);
		return ret;
	}

	/**
	 * get return entity
	 * @param msg
	 * @param code
	 * @return
	 */
	private WSEntity getReturnEntity(String msg, short code) {
		WSEntity ret = WSEntityFactory.getEmptyEntityWithRecords();
		ret.setCode(code);
		ret.setMessage(msg);
		return ret;
	}

}
